﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Models;
using BootstrapAdmin.Web.Core.Services;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal sealed class NoticeService : INoticeService
{
    private readonly IDBManager _dbManager;

    public NoticeService(IDBManager db) => _dbManager = db;

    private const string PLC_Notice_EnergyConsume = nameof(PLC_Notice_EnergyConsume); // 能耗

    public async Task<ApiResult> SaveNoticeAsync(ApiData data)
    {
        // 能耗
        if (data.Exists(PLC_Notice_EnergyConsume))
        {
            return await SaveEnergyConsumeAsync(data);
        }

        return ApiResult.Ok();
    }

    public async Task<ApiResult> SaveEnergyConsumeAsync(ApiData data)
    {
        var energy = data.GetValue<double>(PLC_Notice_EnergyConsume);

        try
        {
            using var db = _dbManager.Create();
            EnergyConsumption item = new()
            {
                Station = data.Schema.Station,
                Energy = (decimal)energy,
                CreatedAt = DateTime.Now,
            };
            await db.InsertAsync(item);
        }
        catch (Exception ex)
        {
            return ApiResult.Error(ex.Message);
        }

        return ApiResult.Ok();
    }
}
